package com.cntv.viewmodeldemo.savestate

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel


/**
 * Created By Mahongyin
 * Date    2020/9/17 17:52
 *
 */
class KTXSaveStateViewModel(private val handle:SavedStateHandle): ViewModel() {
    private val key = "save_key"
    private var _number=MutableLiveData<Int>().also {
        if (!handle.contains(key)) { //如果不包含就是没保存过 判断应该是初始状态 那么给他一个初始值
            handle.set(key, 0) //SavedStateHandle(Map<String, Object> initialState)
        }
        it.value=handle.get(key)
    }

    fun getNum(): MutableLiveData<Int> {
        return _number //handle.getLiveData(key) //将数据来源替换成 VM的SavedStateHandle保存的
    }

    fun add(n: Int) {
        _number.value=_number.value?.plus(n)
//        number.setValue(number.getValue()+n);
        //将数据来源替换给 VM的SavedStateHandle
        handle.set(key,_number.value)
    }
}